0.3.0 4-Tile 5K-Cell Example

In [1]:
import pandas as pd
df = {}
In [2]:
from clustergrammer2 import net

import ipywidgets as widgets
import numpy as np
from bqplot import pyplot as plt
import bqplot

from copy import deepcopy
from glob import glob
from scipy.spatial.distance import pdist, squareform
from scipy.spatial import Voronoi
>> clustergrammer2 backend version 0.4.0

Load Expression Data

In [3]:
net.load_file('../data/processed_data/4-tile_5k-cells_expression-cat.txt')
df['tile-neighbor'] = net.export_df()
df['tile-neighbor'].shape
Out[3]:
(29, 5018)

Load Location Data

In [4]:
net.load_file('../data/processed_data/4-tile_5k-cells_location-cat.txt')
df['tile-loc'] = net.export_df()
df['tile-loc'].shape
Out[4]:
(5146, 2)
In [5]:
cat_colors = net.load_json_to_dict('../data/processed_data/cat_colors.json')
In [6]:
net.load_df(df['tile-neighbor'])
net.set_cat_colors(axis='col', cat_colors=cat_colors, cat_index=1, cat_title='Cell Type')
net.set_cat_colors(axis='col', cat_colors=cat_colors, cat_index=2, cat_title='Neighbor')

Expression Levels of All Cells

In [7]:
net.load_df(df['tile-neighbor'])
net.normalize(axis='row', norm_type='zscore')
net.clip(-5,5)
net.widget()

Expression of B Cells

In [8]:
keep_cols = [x for x in df['tile-neighbor'].columns.tolist() if x[1].split(': ')[1] == 'B cells']
len(keep_cols)
Out[8]:
2826
In [9]:
net.load_df(df['tile-neighbor'][keep_cols])
net.normalize(axis='row', norm_type='zscore')
net.clip(-5,5)
net.widget()

Voronoi Plot

In [10]:
vor = Voronoi(df['tile-loc'])

point_list = df['tile-loc'].index.tolist()
point_names = [x[0] for x in point_list]
cat_names   = [x[1].split(': ')[1] for x in point_list]

patch_data = {}
patch_data['x'] = []
patch_data['y'] = []
patch_data['colors'] = []
region_labels = []

region_point_dict = {}
for point_index in range(vor.point_region.shape[0]):
    region_index = vor.point_region[point_index]
    region_point_dict[region_index] = point_index

for region_index in range(len(vor.regions)):
    
    inst_region = vor.regions[region_index]

    if -1 not in inst_region and len(inst_region) > 0:

        point_index = region_point_dict[region_index]
        point_cat = cat_names[point_index]
        region_labels.append(point_cat)
        
        # save cat_colors
        inst_color = cat_colors[point_cat]
        patch_data['colors'].append(inst_color)
        
        x_list = []
        y_list = []
        for inst_vertex in inst_region:
            inst_pos = vor.vertices[inst_vertex]
            x_list.append(inst_pos[0])
            y_list.append(inst_pos[1])
            
        patch_data['x'].append(x_list)
        patch_data['y'].append(y_list)    
In [11]:
x_dim = 1200
y_dim = 1000

fig = plt.figure(animation_duration=1000)
patch = plt.plot([], [], 
                 fill='inside',
                 fill_colors=patch_data['colors'],
                 stroke_width=1,
                 close_path=True,
                 labels=region_labels,
#                  tooltip=def_tt,
                 axes_options={'x': {'visible': False}, 'y': {'visible': False}},
                )

scatter = plt.scatter(df['tile-loc']['X.X'], 
                      df['tile-loc']['Y.Y'],
#                       tooltip=def_tt, 
                      names=point_names,
                      display_names=False, default_size=2)


inst_width = 950
fig.layout.min_height = str(inst_width/(1.15)) + 'px'
fig.layout.min_width  = str(inst_width) + 'px'

patch.x = patch_data['x']
patch.y = patch_data['y']

plt.xlim(0, 2.0*x_dim)
plt.ylim(0, 2.0*y_dim)

# plt.show()
Out[11]:
LinearScale(max=2000.0, min=0.0)
In [12]:
fig
In [13]:
def mouseover_highlight(self, target):
    # print('cat name', target['data']['name'])
    list_opacities = []
    for inst_label in region_labels:
        inst_opacity = 0.25
        if inst_label == target['data']['name']:
            inst_opacity = 1
        list_opacities.append(inst_opacity)

    self.opacities = list_opacities
In [14]:
def reset_highlight(self, target):
#     print('CLICKING')
    list_opacities = [1 for x in region_labels]
    self.opacities = list_opacities
In [15]:
patch.on_hover(mouseover_highlight)
patch.on_element_click(reset_highlight)
In [ ]: